import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { Logger } from '@nestjs/common';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);
  const logger = new Logger('Bootstrap');

  // 获取配置
  const port = configService.get<number>('port', 3000);
  const globalPrefix = configService.get<string>('globalPrefix', 'api');
  const corsOrigin = configService.get<string>('cors.origin', '*');
  const corsCredentials = configService.get<boolean>('cors.credentials', false);
  const appName = configService.get<string>('app.name', 'WhatToEat API');
  const appVersion = configService.get<string>('app.version', '1.0.0');

  // 设置全局前缀
  app.setGlobalPrefix(globalPrefix);

  // 启用CORS
  app.enableCors({
    origin: corsOrigin,
    credentials: corsCredentials,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'Accept'],
  });

  // 启用关闭钩子
  app.enableShutdownHooks();

  // 启动应用
  await app.listen(port);

  logger.log(`🚀 ${appName} v${appVersion} 启动成功`);
  logger.log(`🌐 服务地址: http://localhost:${port}/${globalPrefix}`);
  logger.log(`📚 API文档: http://localhost:${port}/${globalPrefix}/docs`);
  logger.log(`🔧 环境: ${process.env.NODE_ENV || 'development'}`);
}

bootstrap().catch((error) => {
  const logger = new Logger('Bootstrap');
  logger.error('应用启动失败:', error);
  process.exit(1);
});
